#!/usr/bin/python
'''
edit_frame_name.py

@author: Alessandro Stranieri
'''

import os
import re

if(len(os.sys.argv) < 4):
    print "Wrong parameters number. Exiting..."
    exit(1)

# INPUT PARAMETERS
str_input_directory = os.sys.argv[1]
str_output_directory = os.sys.argv[2]
str_input_file_re = os.sys.argv[3]

def check_directory(str_directory):
    if(os.path.exists(str_directory)):
        print "Input directory <%s> exists." % (os.path.abspath(str_directory))
        return os.path.abspath(str_directory)
    else:
        print "Input directory <%s> does not exist. Exiting..." % (os.path.abspath(str_directory))
        exit(1)

# Check if input and output destination exists
print "Checking existence input and output directories."
str_input_directory = check_directory(str_input_directory)
str_output_directory = check_directory(str_output_directory)

print "Checking content of input directory"
input_file_compiled_re = re.compile(r"%s(?P<frame_index>\w+).png" % (str_input_file_re))

list_input_directory_files = os.listdir(str_input_directory)
# Check if files in the input directory match the given eregexp    
list_matching_input_files = [str_file_name for str_file_name in list_input_directory_files if input_file_compiled_re.match(str_file_name)]
if len(list_matching_input_files) == 0:
    print "No file mathcing the input regular expression found. Exiting..."
    exit(1)
    
list_matching_input_files.sort()
for index, input_file in enumerate(list_matching_input_files):
    input_file_path = os.path.join(str_input_directory, input_file)
    output_file_path = os.path.join(str_output_directory, "myframe_%05d.png" % (index))
    
    print "Renaming %s as %s" % (input_file_path, output_file_path)
    
    os.rename(input_file_path, output_file_path)



    